package com.pet.shop.service.room;

import com.github.pagehelper.Page;
import com.pet.exceptions.BusinessException;
import com.pet.shop.dto.PageDto;
import com.pet.shop.entity.room.Monitor;
import com.pet.shop.entity.room.Room;
import com.pet.shop.mappers.room.MonitorMapper;
import com.pet.shop.mappers.room.RoomMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class RoomServiceImpl implements IRoomService {

    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private MonitorMapper monitorMapper;

    @Override
    public int deleteEntity(Long id) {
        return roomMapper.delete(id);
    }

    @Override
    public int deleteEntityList(List<Long> idList) {
        if(idList == null || idList.isEmpty()) return 0;
        int i = 0;
        for (Long id : idList) {
            i += roomMapper.delete(id);
        }
        return i;
    }

    @Override
    public Room insertEntity(Room record) {
        roomMapper.insert(record);
        record.setStatus(1);
        return record;
    }

    @Override
    public Room getEntity(Long id) {
        return roomMapper.get(id);
    }

    @Override
    public int updateEntity(Room record) {
        if(record == null){
            throw new BusinessException("房间信息为空");
        }
        if(!StringUtils.isEmpty(record.getMonitorSn())){
            Monitor monitor = monitorMapper.queryBySn(record.getMonitorSn());
            if(monitor == null){
                throw new BusinessException("请先添加监控设备，" + record.getMonitorSn() + "不存在!");
            }
            record.setMonitorId(monitor.getId());
        }
        return roomMapper.update(record);
    }

    @Override
    public PageDto<Room> queryPage(PageDto<Room> pageDto) {
        Page<Room> page = roomMapper.queryPage(pageDto);
        pageDto.setPageResult(page);
        return pageDto;
    }
}
